package cn.lg.soar.core.sn;

import cn.lg.soar.core.util.InnerSerializeUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO 可升级为 理想 Lambda 编译版，能提升近百倍性能
 * 可使用预编译缓存模式，可提升近十倍性能
 * @author luguoxiang
 */
@Component
public class SnManagerImpl implements SnManager {

	private Map<String, SnElement> elementMap;

	public SnManagerImpl(List<SnElement> elements) {
		Map<String, SnElement> elementMap = new HashMap<>();
		for (SnElement element : elements) {
			elementMap.put(element.getKey(), element);
		}
		this.elementMap = elementMap;
	}

	@Override
	public String generate(String[] rules, Object... args) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < rules.length; i++) {
			String rule = rules[i];
			int index = rule.indexOf("(");
			if (index == -1) {
				sb.append(elementMap.get(rule).getValue());
				continue;
			}
			// 参数处理
			String params = rule.substring(index + 1, rule.length() - 1);
			Map<Integer, Integer> indexMap;
			if (params.contains("$args[")) {
				String[] split = params.split(",");
				indexMap = new HashMap<>(split.length);
				for (int i1 = 0; i1 < split.length; i1++) {
					String param = split[i1];
					if (param.matches("^\\$args\\[\\d+\\]$")) {
						int idx = Integer.parseInt(param.substring(6, param.length() - 1));
						indexMap.put(i1, idx);
						split[i1] = "0";
					}
				}
				params = String.join(",", split);
			} else {
				indexMap = null;
			}
			// 前缀处理
			if (params.contains("$prefix")) {
				params = params.replace("$prefix", "'" + sb + "'");
			}
			params = '[' + params + ']';
			Object[] os = InnerSerializeUtils.parseObject(params, Object[].class);
			if (indexMap != null) {
				indexMap.forEach((k, v) -> {
					os[k] = args[v];
				});
			}
			rule = rule.substring(0, index);
			sb.append(elementMap.get(rule).getValue(os));
		}
		return sb.toString();
	}

}
